﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using ABCTile.Models;
using ABCTile.DAL;

namespace ABCTile.Controllers
{
    public class AccountController : Controller
    {
        //Database Context
        private ABCDbContext db = new ABCDbContext();
        //
        // GET: /Account/LogOn
        public ActionResult Register()
        {
            ViewBag.RoleID = new SelectList(db.Roles, "RoleID", "RoleName");
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel registerModel)
        {
            ViewBag.RoleID = new SelectList(db.Roles, "RoleID", "RoleName");

            var UserList = db.Users.ToList();

            foreach (var item in UserList)
            {
                if (item.UserID == registerModel.UserName)
                {
                    ViewBag.ErrorMsg = "Try another ID";
                    return View(registerModel);
                }
            }

            User newUser = new User() { 
                UserID = registerModel.UserName, 
                UserPW = registerModel.Password, 
                UserEmail = registerModel.Email, 
                UserFname = registerModel.UserFname, 
                UserLname = registerModel.UserLname, 
                UserMname = registerModel.UserMname, 
                RoleID = registerModel.RoleID
            };

            if (ModelState.IsValid)
            {
                db.Users.Add(newUser);
                db.SaveChanges();
                return RedirectToAction("Index", "Home");
            }

            return View(registerModel);
        }

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (ValidUser(model))
                {
                    User user = db.Users.Find(model.UserName);
                    SetAuthCookieMain(user.UserID, user.Role.RoleName, false, "");

                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }

                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // Valid if user ID and password is valid
        //
        private bool ValidUser(LogOnModel model)
        {
            User user = db.Users.SingleOrDefault(u => u.UserID == model.UserName && u.UserPW == model.Password);
            if (user == null)
            {
                return false;
            }

            return user != null;
        }

        public static void SetAuthCookieMain(string _username, string _role, bool createPersistentCookie, string strCookiePath)
        {
            FormsAuthenticationTicket ticket = CreateAuthenticationTicket(_username, _role, createPersistentCookie, strCookiePath);
            string encrypetedTicket = FormsAuthentication.Encrypt(ticket);
            if (!FormsAuthentication.CookiesSupported)
            {
                FormsAuthentication.SetAuthCookie(encrypetedTicket, false);
            }
            else
            {
                HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName,
                encrypetedTicket);
                authCookie.Expires = ticket.Expiration;
                System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
            }
        }

        private static FormsAuthenticationTicket CreateAuthenticationTicket(string _username, string _roles, bool createPersistentCookie, string strCookiePath)
        {
            string cookiePath = strCookiePath == null ?
                FormsAuthentication.FormsCookiePath : strCookiePath;
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            1,
            _username,
            DateTime.Now,
            DateTime.Now.AddMinutes(30),
            createPersistentCookie,
            _roles,
            cookiePath
            );
            return ticket;
        }
        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
